package com.ysd.twocrm.poicontroller;

import com.ysd.twocrm.entity.Student;
import com.ysd.twocrm.entity.UserRoles;
import com.ysd.twocrm.entity.Users;
import com.ysd.twocrm.mapper.StudentMapper;
import com.ysd.twocrm.mapper.UserRolesMapper;
import com.ysd.twocrm.mapper.UsersMapper;
import com.ysd.twocrm.utils.AddPoiUtils;
import com.ysd.twocrm.utils.MD5Utils;
import com.ysd.twocrm.utils.PoiUtils;
import org.apache.commons.collections4.Get;
import org.apache.commons.collections4.iterators.ObjectGraphIterator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/poiStudent")
public class StudentPoiController {
    @Autowired
    private StudentMapper studentMapper;
    @Autowired
    private UsersMapper usersMapper;
    @Autowired
    private UserRolesMapper userRolesMapper;

    @GetMapping
    public void down(String str, HttpServletResponse response){
        String downLoadName="studentpoi.xlsx";//下载的名字
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/vnd.ms-excel");//指定响应文件为excel
        ServletOutputStream out=null;


        try {
            //文件名编码处理，防止浏览器下载文件名的时候乱码
            response.setHeader("Content-disposition","attachment;filename="+new String(downLoadName.getBytes("GB2312"),"ISO8859-1"));
       out=response.getOutputStream();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
           //通过前端传来的数据生成excel
        List<Student> studentsList=new ArrayList<Student>();
        if(str!=null && str!=""){
            String[] split = str.split(",");
            for(int i=0;i<split.length;i++){
                Student student = studentMapper.selectById(Integer.parseInt(split[i]));
                studentsList.add(student);
            }
        }else{
            studentsList= studentMapper.selectList(null);
        }

        //生成poi
        PoiUtils p=new PoiUtils();

        try {
            p.createExcel(studentsList,Student.class,out);
        } catch (IOException e) {
            e.printStackTrace();
        }


    }




    /*
     * @Description  调用添加的工具类，来获取里面第一行和最后一行数据进行遍历循环，注意第一行一般是表头，所以要第一行来个+1然后来遍历里面的数据
     * 然后通过每次遍历工具类里的数据然后在建立循环，每次都将数据添加进去，添加好了以后任何进行数据库添加即可。
     * 添加学生之前先为他添加一个用户，然后让学生里的用户编号来对应添加的用户id
     * @param spath
     * @return java.lang.Object
     * @author liusupeng
     * @date 2020/4/22 9:37
     */
@PostMapping
    public Object addStudents(String spath){

        try {
            AddPoiUtils addPoiUtils=new AddPoiUtils();
            List<String> stest = addPoiUtils.stest(spath);
            if(stest==null){
                return "nosendexcel";
            }
            int i1=0;//用于读取添加工具类里的内容（下标）
            Integer j=addPoiUtils.getFirstRowNum(spath);
           // System.out.println("第一行"+j);
            Integer j1=addPoiUtils.getLastRomNum(spath);
           // System.out.println("最后一行"+j1);
            List<Student> slist1=new ArrayList<Student>();
            //j+1就是从表格内第二行开始（要跳过表头）
            for(int i=j+1;i<=j1;i++){
                Student stu=new Student(Integer.parseInt(stest.get(i1)),stest.get(++i1),stest.get(++i1),stest.get(++i1),stest.get(++i1),Integer.parseInt(stest.get(++i1)),Integer.parseInt(stest.get(++i1)));
                System.out.println(stu);
                i1++;
                slist1.add(stu);
            }
           int count = 0;
            for(int i=0;i<slist1.size();i++){
                Users u=new Users(0,slist1.get(i).getStudentNo(), MD5Utils.kl(MD5Utils.password("123456")),slist1.get(i).getStudentSex(),slist1.get(i).getStudentName(),0,new Date(),null,0,null,null,null,1,0,0,null);
                      usersMapper.insert(u);//添加用户
                slist1.get(i).setExit1(u.getUserId());//将这个值设置成用户编号id
                 count = studentMapper.insert(slist1.get(i));//添加学生
                //给用户设置角色咯
                Integer studentroleId = userRolesMapper.getAllRoleNameById("学生");//拿到学生的角色id
                UserRoles ur=new UserRoles(0,studentroleId,u.getUserId(),0,0);
                userRolesMapper.insert(ur);//给创建的用户设置角色
            }
            if(count>0){
                return "success";
            }

        } catch (IOException e) {
            e.printStackTrace();
            return "no";
        }catch (Exception e){
            return "sqlno";
        }
    return null;
}

}
